package com.china08.yxyapi.api.manage.tec.office.stuattendance;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.attendance.YxyStuAttendance;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.attendance.YxyStuAttendanceRepository;
import com.china08.yxyapi.util.DateUtils;
import com.china08.yxyapi.util.JpushForMessageUtil;
import com.china08.yxyapi.util.JpushForNotificationUtil;

/**
 * 晨检考勤修改学生状态
 * 
 */
@CrossOrigin
@RestController
public class YxyStuAttendanceUdpController extends YxyApiBaseController {

    @Autowired
    private YxyStuAttendanceRepository yxyStuAttendanceRepository;

    @Value(value = "${yx.rest.api.yx.path}")
    private String yxyApiYxUrl;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/api_yw/manage/tec/office/stuattendance/udp", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel model) {
        YxyStuAttendance yxyStuAttendance;
        if (model.id.trim().equals("")) {
            yxyStuAttendance = new YxyStuAttendance();
            yxyStuAttendance.setId(model.studentId + "_" + DateUtils.formatDate4(new Date()));
            yxyStuAttendance.setStudentId(model.studentId);
            yxyStuAttendance.setStudentName(model.studentName);
            yxyStuAttendance.setAvatar(model.avantar);
            if (model.studentNo != null) {
                yxyStuAttendance.setStudentNo(Long.valueOf(model.studentNo));
            }
            yxyStuAttendance.setClassId(model.classId);
            yxyStuAttendance.setClassName(model.className);
            yxyStuAttendance.setSchoolId(model.schoolId);
            yxyStuAttendance.setSchoolName(model.schoolName);
            yxyStuAttendance.setSignInStatus(0);
            yxyStuAttendance.setSignOutStatus(0);
            yxyStuAttendance.setInspection("未晨检");
            yxyStuAttendance.setSignClass(0);
            yxyStuAttendance.setDayDate(DateUtils.formatDate4(new Date()));
            yxyStuAttendance
                    .setMonthDate(Integer.parseInt(String.valueOf(DateUtils.formatDate4(new Date())).substring(0, 6)));
            yxyStuAttendance
                    .setYearDate(Integer.parseInt(String.valueOf(DateUtils.formatDate4(new Date())).substring(0, 4)));
        } else {
            yxyStuAttendance = yxyStuAttendanceRepository.findOne(model.id);
        }
        if (model.inspection == null) {
            yxyStuAttendance.setSignClass(new Integer(model.signClass));
            yxyStuAttendance.setSignClassDate(new Date());
        } else {
            yxyStuAttendance.setInspection(model.inspection);
            yxyStuAttendance.setInspectionDate(model.inspection.equals("未晨检") ? null : new Date());
        }
        yxyStuAttendanceRepository.save(yxyStuAttendance);

        List<String> stuLst = new ArrayList<String>();
        stuLst.add(model.studentId);

        if (model.inspection != null) {
            if (model.inspection.equals("未晨检")) { return; }
        }

        // 发送推送通知
        try {
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
            Map<String, Object> formMap = new HashMap<String, Object>();
            formMap.put("studentIds", stuLst);
            HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
            StudentParentRespModel httpResult = restTemplate.postForObject(yxyApiYxUrl + "/comm/par/find/stu/parent",
                    formEntity, StudentParentRespModel.class);

            List<StudentParent> studentParents = httpResult.studentParents;
            List<String> perLst = new ArrayList<String>();
            for (StudentParent studentParent : studentParents) {
                perLst.add(studentParent.parentId);

                List<String> stuPerLst = new ArrayList<String>();
                stuPerLst.add(studentParent.parentId);
                // 发送通知
                Map<String, String> mapNotification = new HashMap<String, String>();

                List<String> tabAndList1 = new ArrayList<>();
                tabAndList1.add("PARENTS" + model.schoolId);
                String title = "";
                String alert = "";

                if (model.inspection == null) {
                    alert = "您的孩子（" + studentParent.studentName + "）已到班";
                    title = "考勤到班";
                    mapNotification.put("modelId", "attendanceToStudent");
                } else {
                    alert = "您的孩子（" + studentParent.studentName + "）在校健康状态为：" + model.inspection;
                    title = "晨检健康";
                    mapNotification.put("modelId", "attendanceToStudent");
                }
                JpushForNotificationUtil.sendNotification(alert, title, mapNotification, stuPerLst, tabAndList1);
            }

            // 发送消息
            List<Integer> roleIdList = new ArrayList<>();
            roleIdList.add(1);
            if (model.inspection == null) {
                JpushForMessageUtil.sendMessage(4, roleIdList, model.schoolId, perLst, null);
            } else {
                JpushForMessageUtil.sendMessage(4, roleIdList, model.schoolId, perLst, null);
            }

        } catch (Exception e) {

        }
    }

    /**
     * 请求参数
     * 
     */
    protected static class ReqModel extends YxyApiReqModel {
        // id
        public String id;
        // 晨检状态
        public String inspection;
        // 到班状态
        public String signClass;
        // 学生id
        public String studentId;
        // 学生名称
        public String studentName;
        // 头像
        public String avantar;
        // 学号
        public String studentNo;
        // 班级id
        public String classId;
        // 班级名称
        public String className;
        // 学校id
        public String schoolId;
        // 学校名称
        public String schoolName;

    }

    /**
     * 响应参数
     * 
     */
    protected static class RespModel extends YxyApiRespModel {

    }

    protected static class StudentParentRespModel {
        public List<StudentParent> studentParents;
    }

    protected static class StudentParent {
        public String studentId;
        public String studentName;
        public String parentId;
    }
}
